package com.cms.security;

import java.sql.Connection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.cms.bean.UserBean;
import com.cms.config.MessageDef;
import com.cms.database.DBHelper;
import com.cms.facade.RequestFacade;
import com.cms.facade.SessionFacade;
import com.cms.framework.Command;
import com.cms.framework.CommandException;
import com.cms.user.UserHelper;
import com.cms.util.ApplicationHelper;
import com.cms.util.StringHelper;

public class ConnectCommand implements Command {
	private static final Logger logger = Logger.getLogger(ConnectCommand.class);
	private String next;

	public ConnectCommand(String next) {
		this.next = next;
	}

	@Override
	public String execute(HttpServletRequest req) throws CommandException {
		Connection conn = null;
		String l_next =  this.next;
		int return_code = 0;
		try {
			HttpSession session = req.getSession();
			conn = DBHelper.getConn();
			String user = StringHelper.isEmpty(req.getParameter("user"), "");
			String password = StringHelper.isEmpty(req.getParameter("password"), "");
			String CheckCode =  StringHelper.isEmpty(req.getParameter("check_code"), "");
			
			String session_check_code = (String) session.getAttribute("check_code");
			
			if (StringHelper.isEmpty(session_check_code)
						|| StringHelper.isEmpty(CheckCode)) {
				RequestFacade.setErrorCode(req, -1);
				throw new Exception("验证码不能为空,请重新输入!");
			} else if (!CheckCode.toUpperCase().equals(
					session_check_code.toUpperCase())) {
				RequestFacade.setErrorCode(req, -1);
				throw new Exception("验证码错误，请重新输入新的验证码!");
			}


			return_code = MessageDef.SUCCESS_CODE;

			if (!StringHelper.isEmpty(user) && !StringHelper.isEmpty(password)) {
				
				String encryptpwd = Eryptogram.encryptOp(password,ApplicationHelper.DES_KEY);
				return_code = UserHelper.checkUserLogin(conn, user, encryptpwd);
				RequestFacade.setErrorCode(req, return_code);
				if(return_code>0){
					throw new Exception(MessageDef.getMessageDesc(return_code));	
				}
				
			}else{
				RequestFacade.setErrorCode(req, -1);
				throw new Exception("用户名或者密码不能为空!");
			}

			SessionFacade.setVisitTime(session, (new java.util.Date()).getTime());
			
			UserBean ub = UserHelper.getUserBeanByUser(conn, user);
			
			SessionFacade.setUserBean(session, ub);
			SessionFacade.setIsSysAdmin(session, ub.getAdminType());
			
		} catch (Exception e) {
			l_next = "/jsp/login.jsp";
			throw new CommandException(req, e.getMessage());
		} finally{
			DBHelper.closeConn(conn);
		    return l_next;
		}
	}

}
